<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload with Axios</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f7f7f7;
            padding: 20px;
        }
        form {
            background: white;
            max-width: 500px;
            margin: auto;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        input[type="file"] {
            margin-bottom: 10px;
        }
        button {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        #show {
            margin-top: 20px;
            width: 100%;
            padding: 10px;
        }
    </style>
</head>

<body>
<form id="uploadForm">
    <input type="file" id="file" name="file"/>
    <button type="button" onclick="uploadFile()">Upload</button>
</form>
<div id="progressContainer" style="display:none;">
    <div>上传进度: <span id="progress">0%</span></div>
    <div>记住这个id：</div>
    <input type="text" id="show" readonly/>
</div>

<script>
    function uploadFile() {
        const fileInput = document.getElementById('file');
        const file = fileInput.files[0];

        if (!file) {
            alert('请选择一个文件');
            return;
        }

        const formData = new FormData();
        formData.append('file', file);

        const progressContainer = document.getElementById('progressContainer');
        const progressSpan = document.getElementById('progress');
        progressContainer.style.display = 'block';
        progressSpan.textContent = '0%';

        axios.post('http://127.0.0.1:8004/index/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            onUploadProgress: progressEvent => {
                const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                progressSpan.textContent = percentCompleted + '%';
            }
        })
            .then(response => {
                const {code, data, message} = response.data;
                if (code === "2000") {
                    alert('上传成功，结果: ' + message);
                    var show = document.getElementById('show');
                    show.value = data;
                } else {
                    alert('上传失败，错误信息: ' + message);
                }
            })
            .catch(error => {
                console.error('上传过程中发生错误:', error);
                alert('上传过程中发生错误');
            });
    }
</script>
</body>
</html>
